package com.spoplar.assistant;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Iterator;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import redis.clients.jedis.Jedis;

public class ItemServlet extends HttpServlet {
	private Jedis jedis;
	

	/**
	 * Initialization of the servlet. <br>
	 *
	 * @throws ServletException if an error occurs
	 */
	public void init() throws ServletException {
		jedis = new Jedis("127.0.0.1",6379);
		jedis.select(5);
	}
	/**
	 * The doPost method of the servlet. <br>
	 *
	 * This method is called when a form has its tag value method equals to post.
	 * 
	 * @param request the request send by the client to the server
	 * @param response the response send by the server to the client
	 * @throws ServletException if an error occurred
	 * @throws IOException if an error occurred
	 */
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		response.setCharacterEncoding("UTF-8");
		response.setContentType("text/json");
		PrintWriter out = response.getWriter();
		String route_id = request.getParameter("route_id");
		JSONObject tmp = null;
		
		String didi_route_lists = jedis.get("didi_route_lists");
		JSONArray route_jarr = JSON.parseArray(didi_route_lists);
		for(Iterator iterator = route_jarr.iterator();iterator.hasNext();){
			 JSONObject obj =(JSONObject)iterator.next();
			 String t_route_id = obj.getString("route_id");
			 if(route_id.equals(t_route_id)){
				 tmp = obj;
				 break;
			 }
		}
		
		String didi_suspense_list = jedis.get("didi_suspense_list");
		JSONArray suspense_jarr = JSON.parseArray(didi_suspense_list);
		if(tmp == null){
			for(Iterator iterator = suspense_jarr.iterator();iterator.hasNext();){
				 JSONObject obj =(JSONObject)iterator.next();
				 String t_route_id = obj.getString("route_id");
				 if(route_id.equals(t_route_id)){
					 tmp = obj;
					 break;
				 }
			}
		}
		
		StringBuffer buff = new StringBuffer();
		buff.append("{");
		if(tmp == null){
			buff.append("'code'").append(":").append("'NO'").append(",");
			buff.append("'data'").append(":").append("");
		}else{
			buff.append("'code'").append(":").append("'OK'").append(",");
			buff.append("'data'").append(":").append(tmp.toJSONString());
		}
		
		buff.append("}");
		out.println(buff.toString());
		out.flush();
		out.close();
	}
	/**
	 * Destruction of the servlet. <br>
	 */
	public void destroy() {
		super.destroy(); // Just puts "destroy" string in log
		if(jedis !=null){
			try{
				jedis.close();
				jedis = null;
			}catch(Exception $e){
				System.out.println($e.getMessage().toString());
			}finally{
				jedis.close();
				jedis = null;
			}
		}
	}
}
